﻿using Mapster;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Zhp.Common.Exception;
using Zhp.Common.Helper;
using Zhp.Entity.Message.Email;
using Zhp.IService.Message.Email;
using Zhp.Model.Message.Email;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Message.Email
{
    public class EmailTemplateService : BaseService<EmailTemplate>, IEmailTemplateService
    {
        private readonly IEmailSender _emailSender;
        private readonly IEmailTemplateRender _emailTemplateRender;
        public EmailTemplateService(IBaseRepository<EmailTemplate> rep, IEmailSender emailSender, IEmailTemplateRender emailTemplateRender) 
        { 
            _rep = rep;
            _emailSender = emailSender;
            _emailTemplateRender = emailTemplateRender;
        }

        public async Task<List<EmailTemplateModel>> Query(QueryEmailTemplateParam p)
        {
            var emailList = await _rep.GetPageListAsync(new List<IConditionalModel>
            {

            }, p, x => x.CreateTime, OrderByType.Desc);
            return await _rep.AsQueryable().LeftJoin<EmailAccount>((x, y) => x.EmailAccountId == y.Id).OrderByDescending(x => x.CreateTime).Select<EmailTemplateModel>().ToPageListAsync(p.PageIndex, p.PageSize, p.TotalCount);
        }

        public async Task<bool> Create(EditEmailTemplateParam p)
        {
            if (await _rep.IsAnyAsync(x => x.Name == p.Name))
            {
                throw new AlertException($"模板名称=>{p.Name}=>已存在!");
            }
            var tpl = p.Adapt<EmailTemplate>();
            return await _rep.InsertAsync(tpl);
        }

        public async Task<bool> Update(EditEmailTemplateParam p)
        {
            if (await _rep.CountAsync(x => x.Name == p.Name) > 1)
            {
                throw new AlertException($"模板名称=>{p.Name}=>已存在!");
            }
            var tpl = await _rep.GetByIdAsync(p.Id);
            if (tpl != null)
            {
                p.Adapt(tpl);
                return await _rep.UpdateAsync(tpl);
            }
            return false;
        }

        public async Task<bool> Delete(long id)
        {
            return await _rep.DeleteByIdAsync(id);
        }

        public async Task<bool> TestSendEmail(TestSendEmailParam p)
        {
            var tpl = await _rep.GetByIdAsync(p.Id);
            var type = _emailTemplateRender.GetVariableClassType(tpl.VariableClass);
            type = JToken.Parse(p.EmailData).Type == JTokenType.Array ? type = type.MakeArrayType() : type;
            var emailData = JsonConvert.DeserializeObject(p.EmailData, type);
            var ret = await _emailSender.SendEmailAsync(tpl.Name, emailData, p.ToEmailAddress, p.ToEmailName);
            return await Task.FromResult(ret);
        }

        public async Task<(Stream, string, string)> ExportExcel()
        {
            var list = await _rep.GetListAsync();

            return await ExcelHelper.Export(list.Adapt<List<EmailTemplateExcel>>());
        }

        public async Task<bool> ImportExcel(Stream stream)
        {
            var excelData = await ExcelHelper.Import<EmailTemplateExcel>(stream);

            return await _rep.InsertRangeAsync(excelData.Adapt<List<EmailTemplate>>());
        }
    }
}
